package com.sixuerain.heartkey.prayer.db;

import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public abstract class BaseDAO<T> extends DBConnect {
	
		
	public BaseDAO(Context context) {
		super(context);
	}

	public T singleSearch(String table,
			String[] columns, String selection, String[] selectionArgs,
			String groupBy, String having, String orderBy, String limit) {
		T object = null;

		final Cursor cursor = this.getReadableDB().query(table, columns, selection,
				selectionArgs, groupBy, having, orderBy, limit);
		try {
			if (cursor.moveToFirst()) {
				object = this.mapRow(cursor, cursor.getCount());
			}
		} finally {
			cursor.close();
		}
		return object;
	}
	
	public List<T> multiSearch(String table,
			String[] columns, String selection, String[] selectionArgs,
			String groupBy, String having, String orderBy, String limit) {
		List<T> list = new ArrayList<T>();

		final Cursor cursor = this.getReadableDB().query(table, columns, selection,
				selectionArgs, groupBy, having, orderBy, limit);
		try {
			while (cursor.moveToNext()) {
				list.add(mapRow(cursor, 1));
			}
		} finally {
			cursor.close();
		}
		return list;
	}
	
	public int update(String table,ContentValues values
			,String whereClause,String[] whereArgs) {
		return this.getWritableDB().update(table, values, whereClause, whereArgs);
	}
	
	public int updateByField(String table,ContentValues values,String field,String fieldValue) {
		return this.update(table, values,
				field + "=?", new String []{fieldValue});
	}
	
	public int updateByFields(String table,ContentValues values,String[] fields,String[] fieldValues) {
		StringBuffer cond = new StringBuffer();
		if(fields!=null&&fields.length>0) {
			for(String field:fields) {
				if(cond.length()>0)
					cond.append(" and ").append(field).append("=?");
				else
					cond.append(field).append("=?");
			}
			return this.update(table, values,cond.toString(), fieldValues);
		}
		return this.update(table, values, null, null);
	}
	
	/**
	 * delete data by a field
	 * @param table
	 * @param field
	 * @param value
	 * @return
	 */
	public int deleteByField(String table, String field, String value) {
		return this.getWritableDB().delete(table, field + "=?", new String[] { value });
	}
	
	public int deleteByFields(String table, String whereClause, String[] whereArgs) {
		return this.getWritableDB().delete(table, whereClause, whereArgs);
	}


	
	public long insert(String table,ContentValues values) {
		return this.getWritableDB().insert(table, null, values);

	}
	
	public void executeSQL(String sql,List params) {
		this.getWritableDB().execSQL(sql, params.toArray());
	}
	
	public abstract T mapRow(Cursor cursor, int rowNum);
	
}
